<template>
  <!--  查询框区-->
  <div class="search">
    <el-form inline :model="coachSearchModel" ref="coachSearchForm">
      <el-form-item label="教练姓名: ">
        <el-input v-model="coachSearchModel.name" placeholder="请输入教练姓名" clearable/>
      </el-form-item>
      <el-form-item label="手机号: ">
        <el-input v-model="coachSearchModel.phone" placeholder="请输入手机号" clearable/>
      </el-form-item>
      <el-form-item label="微信号: ">
        <el-input v-model="coachSearchModel.wechat" placeholder="请输入微信号" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="search()">查询</el-button>
        <el-button :icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>


  <!--  按钮区 -->
  <div class="action">
    <el-button type="primary" :icon="CirclePlus" @click="add">新增</el-button>
    <el-button type="primary" :icon="Edit" @click="edit">修改</el-button>
    <el-button type="danger" :icon="Delete" @click="remove()">删除</el-button>
  </div>


  <!--  表格区-->
  <div class="grid">
    <el-table :data="coaches"
              stripe
              border
              @row-click="tblRowClick"
              ref="tblRef"
              class="coach-table"
              v-loading="loading"
              element-loading-text="数据加载中...">
      <el-table-column type="selection" align="center" width="55"/>
      <el-table-column prop="id" label="编号" align="center" width="80"/>
      <el-table-column prop="photo" label="照片" fixed width="120">
        <template #default="scope">
          <div class="img" :style="'background-image:url('+(baseUrl+scope.row.photo)+')'">
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" align="center" width="120"/>
      <el-table-column prop="phone" label="手机号" width="150"/>
      <el-table-column prop="wechat" label="微信号" width="150"/>
      <el-table-column prop="recomm" label="个人介绍" min-width="300"/>
      <el-table-column label="操作" width="160" align="center" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click.stop="editRow(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click.stop="deleteRow(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>


  <!--  添加、修改弹出表单-->
  <el-dialog :title="coachDlgTiele" v-model="coachDlgShow" draggable align-center :close-on-click-modal="false"
             @close="resetCoachForm" width="600px">
    <el-form label-width="100" label-position="right" :model="coachModel" ref="coachFormRef">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form-item prop="name" label="姓名：" :rules="[{ required: true, message: '请输入教练姓名', trigger: 'blur' }]">
            <el-input v-model="coachModel.name" placeholder="请输入教练姓名"/>
          </el-form-item>
          <el-form-item prop="phone" label="手机号： " :rules="[{ required: true, message: '请输入教练手机号', trigger: 'blur' }]">
            <el-input v-model="coachModel.phone" placeholder="请输入教练手机号"/>
          </el-form-item>
          <el-form-item prop="wechat" label=" 微信号：">
            <el-input v-model="coachModel.wechat" placeholder="请输入教练微信号"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-upload drag
                     class="avatar-uploader"
                     action="/api/coach/avatar"
                     :on-success="photoUploadSuccess"
                     :show-file-list="false"
                     :headers="headers">
            <div class="img" v-if="coachModel.photo" :style="'background-image:url('+(baseUrl+coachModel.photo)+')'">
            </div>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
          <div class="upload-tip">点击上传或拖拽图片</div>
        </el-col>
      </el-row>
      <el-form-item prop="recomm" label="个人介绍：" :rules="[{ required: true, message: '请输入教练个人介绍', trigger: 'blur' }]">
        <el-input v-model="coachModel.recomm" type="textarea" placeholder="请输入教练个人介绍" :rows="5"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <div>
        <el-button @click="coachDlgShow=false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!--  分页区-->
  <div class="pagination">
    <el-pagination
        v-model:current-page="coachesPi.pageNo"
        v-model:page-size="coachesPi.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="coachesPi.total"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
    />
  </div>
</template>

<style scoped>
.img {
  width: 80px;
  height: 80px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  border-radius: 8px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  margin: 5px auto;
}

.img:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.15);
}

.search {
  padding: 20px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.search .el-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  position: sticky;
  top: 0;
  z-index: 10000;
}

.search .el-form-item {
  margin-bottom: 0;
}

.search .el-form-item:last-child {
  margin-left: auto;
}

.action {
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 84px;
  z-index: 99;
  display: flex;
  gap: 12px;
}

.grid {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
}

.coach-table {
  margin-top: 10px;
  width: 100%;
}

.coach-table :deep(.el-table__cell) {
  padding: 8px 0;
}

.coach-table :deep(th.el-table__cell) {
  background-color: #f5f7fa;
  color: #333;
  font-weight: 500;
}

.coach-table :deep(.el-table__row:hover) {
  background-color: #f0f8ff;
}

.coach-table :deep(.el-table__row) {
  height: 100px;
}

.el-dialog {
  border-radius: 8px;
}

.el-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #e6e6e6;
  margin-right: 0;
  padding: 15px 20px;
}

.el-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.el-dialog :deep(.el-dialog__footer) {
  border-top: 1px solid #e6e6e6;
  padding: 15px 20px;
}

.el-form-item {
  margin-bottom: 18px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
}

.el-button {
  transition: all 0.3s;
}

.el-button + .el-button {
  margin-left: 12px;
}

.el-button--primary {
  background-color: #1e3c72;
  border-color: #1e3c72;
}

.el-button--primary:hover {
  background-color: #2a5298;
  border-color: #2a5298;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(30, 60, 114, 0.2);
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.el-button--danger:hover {
  background-color: #f78989;
  border-color: #f78989;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(245, 108, 108, 0.2);
}

.el-input__inner,
.el-textarea__inner {
  border-radius: 4px;
  transition: all 0.3s;
}

.el-input__inner:focus,
.el-textarea__inner:focus {
  box-shadow: 0 0 0 2px rgba(30, 60, 114, 0.2);
}

.avatar-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  margin: 0 auto;
}

.avatar-uploader:hover {
  border-color: #1e3c72;
  box-shadow: 0 2px 12px 0 rgba(30, 60, 114, 0.2);
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-tip {
  text-align: center;
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}

/* 添加滚动条样式 */
.grid::-webkit-scrollbar {
  width: 6px;
}

.grid::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 3px;
}

.grid::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}
</style>


<script setup>
import {onMounted, reactive, ref, toRaw, nextTick} from "vue"
import api from "@/utils/api.js";
import {CirclePlus, Delete, Edit, Plus, Refresh, Search} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {cloneDeep} from "lodash";
import {getJwt} from "@/api/jwt.js";

const headers = {"Authorization": getJwt()}
const loading = ref(false)
//查询区
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 表格数据模型
let coaches = ref()

// 表单模型
let coachSearchForm = ref()
// 表格对象
let tblRef = ref()

// 分页数据模型
let coachesPi = reactive({
  pageNo: 1,
  pageSize: 7,
  total: 0
})

//教练查询条件模型
let coachSearchModel = ref({
  name: "",
  phone: "",
  wechat: ""
})


//查询全部教练,按条件查询
async function search(pageNo = 1, pageSize = 7, params) {
  loading.value = true
  params = coachSearchModel.value
  try {
    let resp = await api({
      url: "/coach",
      method: "get",
      params: {
        pageNo,
        pageSize,
        ...params
      }
    });
    coaches.value = resp.data.records
    coachesPi.total = resp.data.total
    coachesPi.pageNo = resp.data.current
    coachesPi.pageSize = resp.data.size
  } catch (error) {
    ElMessage.error("查询失败: " + error.message)
  } finally {
    loading.value = false
  }
}

//重置
function reset() {
  coachSearchModel.value = {
    name: "",
    phone: "",
    wechat: ""
  }
  search()
}


//删除教练
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 表格行点击
function tblRowClick(row) {
  tblRef.value.toggleRowSelection(row)
}

//删除
function remove() {
  let rows = tblRef.value.getSelectionRows();
  if (rows.length === 0) {
    ElMessage.warning("请选择要删除的行")
  } else {
    ElMessageBox.confirm(`确定要删除选中的 ${rows.length} 位教练吗？`, "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      let ids = rows.map(item => item.id);
      deleteCoachById(ids);
    }).catch(() => {
      ElMessage.info("已取消删除")
    })
  }
}

//删除教练
async function deleteCoachById(ids) {
  try {
    let resp = await api({
      url: "/coach",
      method: "delete",
      data: ids
    })

    if (resp.success) {
      ElMessage.success("删除成功")
      search();
    } else {
      ElMessage.error("删除失败: " + resp.message)
    }
  } catch (error) {
    ElMessage.error("删除失败: " + error.message)
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//新增教练
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
let coachDlgTiele = ref("新增教练")
let coachDlgShow = ref(false)
let mode = "add"

// 教练模型
let coachModel = ref({
  name: null,
  phone: null,
  wechat: null,
  recomm: null,
  photo: null
})

let coachFormRef = ref();

// 打开新增弹窗
function add() {
  coachDlgShow.value = true
  coachDlgTiele.value = "新增教练"
  mode = "add";
}

function submit() {
  coachFormRef.value.validate((valid) => {
    if (valid) {
      if (mode === "add") {
        submitAdd();
      } else if (mode === "edit") {
        submitEdit();
      }
    } else {
      ElMessage.warning("请填写必填项");
      return false;
    }
  });
}

// 提交新增
async function submitAdd() {
  try {
    let params = toRaw(coachModel.value);
    let resp = await api({
      url: "/coach",
      method: "post",
      data: params
    })

    if (resp.success) {
      coachDlgShow.value = false
      search()
      ElMessage.success("添加成功")
    } else {
      ElMessage.error("添加失败: " + resp.message)
    }
  } catch (error) {
    ElMessage.error("添加失败: " + error.message)
  }
}

//重置表单
function resetCoachForm() {
  coachFormRef.value.resetFields();
  coachModel.value = {
    name: null,
    phone: null,
    wechat: null,
    recomm: null,
    photo: null
  }
}

//修改表单
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function edit() {
  let row = tblRef.value.getSelectionRows();
  if (row.length === 0) {
    ElMessage.warning("请选择要修改的行")
  } else if (row.length > 1) {
    ElMessage.warning("只能选择一行")
  } else {
    mode = "edit"
    coachDlgShow.value = true
    coachDlgTiele.value = "修改教练信息"
    nextTick(() => {
      coachModel.value = cloneDeep(toRaw(row[0]));
    })
  }
}

async function submitEdit() {
  try {
    let params = toRaw(coachModel.value);
    let resp = await api({
      url: "/coach",
      method: "PUT",
      data: params
    });

    if (resp.success) {
      ElMessage.success("教练信息修改成功")
      coachDlgShow.value = false
      search();
    } else {
      ElMessage.error("修改失败: " + resp.message)
    }
  } catch (error) {
    ElMessage.error("修改失败: " + error.message)
  }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//操作区按钮
function editRow(row) {
  coachDlgShow.value = true;
  coachDlgTiele.value = "修改教练信息"
  mode = "edit"
  nextTick(() => {
    coachModel.value = cloneDeep(toRaw(row))
  })
}

function deleteRow(row) {
  ElMessageBox.confirm(`确定要删除教练 ${row.name} 吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteCoachById([row.id]);
  }).catch(() => {
    ElMessage.info("已取消删除")
  })
}

// 分页切换
function handlePageChange(pageNo) {
  search(pageNo, coachesPi.pageSize);
}

function handleSizeChange(pageSize) {
  coachesPi.pageSize = pageSize
  search(1, pageSize);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import baseUrl from "@/utils/constant.js";

//上传头像成功
function photoUploadSuccess(resp) {
  let url = resp.data;
  coachModel.value.photo = url;
  ElMessage.success("头像上传成功")
}

onMounted(() => {
  search();
})
</script>
